    企微导购码管理
<template>
  <a-card :bordered="false">
  <!-- 注释的为暂时未开发的功能，不能删 -->
  <!-- 欢迎语规则管理 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline"  @keyup.enter.native="searchQuery">
        <a-row :gutter="12">
          <a-col :md="4" :sm="8">
            <a-form-item label="编号" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <!-- <a-input placeholder="请输入" v-model="queryParam.id"></a-input> -->
              <a-input v-model="queryParam.id" placeholder="请输入" allowClear onkeyup="this.value=this.value.replace(/\D/g,'')" onafterpaste="this.value=this.value.replace(/\D/g,'')" />
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="姓名" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-input placeholder="请输入" v-model="queryParam.name"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="员工ID" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-input placeholder="请输入" v-model="queryParam.userId"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="手机号" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-input placeholder="请输入" v-model="queryParam.mobile"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="门店编码" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-input placeholder="请输入" v-model="queryParam.storeCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="门店名称" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-input placeholder="请输入" v-model="queryParam.storeName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="品牌" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-select ref="select" v-model="queryParam.brandName" placeholder="请选择" allowClear>
                <a-select-option :value="item.brandName" v-for="(item, index) in brandOption" :key="index">{{ item.brandName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <a-form-item label="人员类型" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-select ref="select" mode="multiple"  
                v-model="aaa" 
                placeholder="请选择" 
                allowClear
              >
                <a-select-option :value="item.name" v-for="(item, index) in ryOption" :key="index">{{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

           <a-col :md="4" :sm="8">
            <a-form-item label="门店类型" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-select ref="select" v-model="queryParam.storeType" placeholder="请选择" allowClear>
                <a-select-option :value="item.value" v-for="(item, index) in mdtypeOption" :key="index">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--<a-col :md="4" :sm="8">
            <a-form-item label="区部" :labelCol="{ span: 6 }" :wrapperCol="{ span: 14, offset: 0 }">
              <a-select ref="select" v-model="queryParam.status" placeholder="请选择" allowClear>
                <a-select-option :value="item.value" v-for="(item, index) in qbOption" :key="index">{{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button  @click="hyy" icon="search">欢迎语设置-门店包应用</a-button>
              <a-button  @click="handlesync" icon="reload" style="margin-left: 8px">同步数据</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>

      <!-- <div class="table-operator" style="border-top: 5px">
        <a-button type="primary" @click="handleAdd">新增</a-button>
      </div> -->
      <a-tabs type="card" @change="callback" :defaultActiveKey="queryParam.type">
        <a-tab-pane key="1" tab="已设置规则">
        </a-tab-pane>
        <a-tab-pane key="2" tab="未设置规则">
        </a-tab-pane>
      </a-tabs>

      <a-table
        ref="table"
        rowKey="key"
        size="middle"
        :columns="columns"
        :row-selection="rowSelection"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        @change="handleTableChange">
        <span slot="xxneirong" slot-scope="text, record">
          <a @click="xiaoxi(record)" style="text-decoration:underline;color:#000000A6;">
            {{record.xxneirong}}
          </a>
        </span>
        <span slot="action" slot-scope="text, record">
          <a @click="clickewm(record)">
            <a-icon type="" />
            查看二维码
          </a>
          <a-divider type="vertical" v-show="record.welcomeId !== -1" />
          <a @click="handelecreat(record)" v-show="record.welcomeId !== -1">
            <a-icon type=""/>
            查看规则
          </a>
        </span>
      </a-table>
      <a-button type="link" @click="selectAll" v-show="selectshow">全选</a-button>
      <div v-show="qxselectshow || selectedTableRow.length > 0">
        <a-button type="link" @click="unselect">取消全选</a-button>
        <a-button type="" @click="sethyyrule" style="margin-right:10px;">设置欢迎语规则</a-button>
        <a-button type="" @click="downloadewm">下载二维码</a-button>
      </div>
    </div>

    <!-- 企微导购码欢迎语规则 -->
    <a-modal v-model="qwrulevisible" title="提示" @ok="qwruleOk" width="460px">
      <div class="qwruletitle">请选择对应企微导购码欢迎语规则</div>
      <a-select 
        show-search
        v-model="welcomeId" 
        :show-arrow="false"
        :filter-option="filterOption"
        @change="qwruleChange" 
        @blur="handleExpressBlur"
        placeholder="请选择" 
        style="width:250px;margin-right: 20px;" 
        allowClear
      >
        <a-select-option 
          :value="item.id" 
          v-for="item in qwruleList" 
          :key="item.id"
        > 
          {{ item.name }} 
        </a-select-option>
      </a-select>
      <a 
        href="#" 
        @click.prevent="ruledetail" 
        :disabled="welcomeId == '' || welcomeId == undefined
        "
        class="detailbox" 
      >查看规则细节</a>
      <div class="detailbox1" v-show="rushow">
        <div class="item" v-if="qwruledetail.content.length !== 0" style="margin-top:10px;">
          <div>文字消息:</div>
          <!-- <div class="content" v-for="content,index in qwruledetail.content" :key="index">{{content}}</div> -->
          <div class="card-info" v-for="(item, index) in cardInfo" :key="index">
            <p v-html="formatCardInfo(item)"></p>
          </div>
        </div>

        <div  class="item" v-if="qwruledetail.imageUrl.length !== 0">
          <div>图片消息:</div>
          <img :src="imageUrl" alt="" class="content"  v-for="imageUrl,index in qwruledetail.imageUrl" :key="index">
        </div>

        <div v-for="miniProgramDto,index in qwruledetail.miniProgramDto" :key="index">
          <div>小程序卡片消息:</div>
          <div class="content" v-if="miniProgramDto.text !==''&& miniProgramDto.text !== undefined">
            <div >{{miniProgramDto.text}}</div>
          </div>

          <div class="content" v-if="miniProgramDto.appId !=='' && miniProgramDto.appId !== undefined">
            <div>APPID:{{miniProgramDto.appId}}</div>
          </div>

          <div class="content" v-if="miniProgramDto.url !=='' && miniProgramDto.url !== undefined">
            <div>路径:{{miniProgramDto.url}}</div>
          </div>

          <div class="content" v-if="miniProgramDto.title !=='' && miniProgramDto.title !== undefined">
            <div>标题:{{miniProgramDto.title}}</div>
          </div>

          <div v-if="miniProgramDto.image !=='' && miniProgramDto.image !== undefined">
            <img :src="miniProgramDto.image" alt="" class="content">
          </div>
        </div>
      </div>
    </a-modal>
    <!-- 下载中心 -->
    <a-modal v-model="visible" title="下载中心" @ok="handleOk" width="1000px">
      <!-- <div class="downloadTitle">下载中心</div> -->
      <a-table 
        :columns="downcolumns" 
        :data-source="downloadSource"  
        :pagination="downloadipag"
        :loading="loading"
        @change="handleTableChange1"
       >
        <span slot="action" slot-scope="text, record">
          <a @click="dfLoad(record)" :disabled="record.status !== 1 || record.url == ''" v-if="record.type == 1">
            <a-icon type="edit"/>
            下载
          </a>
          <a :disabled="record.status !== 1 || record.url == ''" v-else @click="downloadIamge(record.url,record.name)">
            <a-icon type="edit"/>
            下载
          </a>
        </span>
      </a-table>
    </a-modal>
    <!-- 下载icon -->
    <img src="https://img.bzhz.jnbygroup.com/dincandownload.png" alt="" class="download" @click="downloadicon">
    <!-- 查看二维码 -->
    <a-modal title="二维码" :dialog-style="{ top: '200px' }" :visible="removeVisible" @ok="clickCode()" okText="下载"  @cancel="() => (removeVisible = false)">
      <img
        style="width: 200px;height:200px;margin-left: 129px;"
        :src="qrCode"
      />
    </a-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { filterObj } from '@/utils/util';
import { syncData, AllCpWelcome, getWelcomeVoById, setWelcomeBatch, brandList,downloadQrcode, downloadQrcodeBatch, pageDownloadVo  } from '@/api/marketingCenter/code'
import { trueDependencies } from 'mathjs';

export default {
  name:'qw',
  mixins:[JeecgListMixin],
  components: { 
    // contentmodel
  },
  data() {
    return {
      doubleArr:[],
      ryOption:[
        {
          name:'其他',
          value:'其他',
        },
        {
          name:'托管',
          value:'托管',
        },
        {
          name:'总部编制外',
          value:'总部编制外',
        },
        {
          name:'工厂',
          value:'工厂',
        },
        {
          name:'香港',
          value:'香港',
        },
        {
          name:'直营',
          value:'直营',
        },
        {
          name:'总部',
          value:'总部',
        },
        {
          name:'外包',
          value:'外包',
        },
        {
          name:'经销',
          value:'经销',
        },
        {
          name:'慧展',
          value:'慧展',
        },
      ],
      qrCode:'',
      qrCodeName:'',
      selectedTableRow: [], // table 全选选中id
      selectshow: true,
      qxselectshow: false,
      rushow: false,
      brandOption: [], // 品牌
      qbOption: [], // 区部
      mdtypeOption: [
        {
          label:'奥莱',
          value:1,
        },
        {
          label:'正价',
          value:2,
        }
      ], // 门店类型
      // 企微导购码欢迎语规则
      qwruleList: [], 
      welcomeId: '', // 企微导购码欢迎语规则下拉选中
      qwrulevisible: false,
      qwruledetail:{
        // miniProgramDto:{},
        // content:'',
        // imageUrl:'',
        miniProgramDto:[],
        content:[],
        imageUrl:[],
      },
      visible:false,
      removeVisible: false,
      queryParam:{
        current: 1,
        size: 10,
        type:1
      },
      // 表头
      columns: [
        {
          title: '编号',
          align: "center",
          dataIndex: 'id',
        },
        {
          title: '姓名',
          align: "center",
          dataIndex: 'name',
        },
        {
          title: '员工ID',
          align: 'center',
          dataIndex: 'userId',
        },
        {
          title: '职务',
          align: 'center',
          dataIndex: 'position',
        },
        {
          title: '性别',
          align: 'center',
          dataIndex: 'sex',
        },
        {
          title: '手机号',
          align: 'center',
          dataIndex: 'mobile',
        },
        {
          title: '是否设置规则',
          align: 'center',
          dataIndex: 'welcomeText',
        },
        {
          title: '品牌',
          align: 'center',
          dataIndex: 'brandName',
        },
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'linkstore',
        },
        {
          title: '人员类型',
          align: 'center',
          dataIndex: 'wxopenid',
        },
        // {
        //   title: '门店编码',
        //   align: 'center',
        //   dataIndex: 'mdbm',
        // },
        // {
        //   title: '区部',
        //   align: 'center',
        //   dataIndex: 'linksource',
        // },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'storeName',
        },
        {
          title: '门店类型',
          align: 'center',
          dataIndex: 'storeType',
        },
        {
          title: '操作',
          align: "center",
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
        }
      ],
      downcolumns:[
        {
          title: '任务名称',
          align: "center",
          dataIndex: 'name',
        },
        {
          title: '下载时间',
          align: "center",
          dataIndex: 'createTime',
        },
        {
          title: '文件大小',
          align: "center",
          dataIndex: 'fileSize',
        },
        {
          title: '下载状态',
          align: "center",
          dataIndex: 'statusText',
        },
        {
          title: '操作',
          align: "center",
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
        }
      ],
      aaa:["直营","经销"],
      downloadSource:[],
      downloadipag:{
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['2', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        total: 0
      },
      ids:'',
      url: {
        list: "/backend/qrcode/pageMemberVo",
      },
      cardInfo: [],
    }
  },
  computed: {
    rowSelection () {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedTableRow = selectedRowKeys
          if (selectedRows.length >= 0) {
            this.selectshow = false
            let ids = selectedRows.map((el,index) =>{
              return el.id
            })
            this.ids = ids.join(',')
          }
          console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        selectedRowKeys: this.selectedTableRow
      }
     },
    formattedCardInfo() {
      const lines = this.content.join("\n")
      let result = ""
      const parser = new DOMParser()
      const doc = parser.parseFromString(lines, "text/html")
      const nodes = doc.body.childNodes
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.nodeName === "#text") {
          result += node.textContent
        } else if (node.nodeName === "A") {
          result += `<a href="#">${node.textContent}</a>`
        }
      }
      return result
    }
  },
  created() {
    this.getBrandList()
    this.handlesync1()
  },
  methods: {
    formatCardInfo(item) {
      let result = ""
      const parser = new DOMParser()
      const doc = parser.parseFromString(item, "text/html")
      const nodes = doc.body.childNodes
      for (let i = 0; i < nodes.length; i++) {
        const node = nodes[i]
        if (node.nodeName === "#text") {
          result += node.textContent.replace(/\n/g, '<br>')
        } else if (node.nodeName === "A") {
          result += `<a href="#">${node.textContent}</a>`
        }
      }
      return result
    },
    // 下载二维码zip
    dfLoad(file) {
      this.getBlob(file.url).then(blob => {
        this.DownloadItem(blob, file.name);
      });
    },
    getBlob(url) {
      return new Promise(resolve => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onload = () => {
          if (xhr.status === 200) {
            resolve(xhr.response);
          }
        };
        xhr.send();
      });
    },
    DownloadItem(blob,fileName){
      let link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
    },
    // zip结束
    getQueryParams() {
      if (this.aaa.length !== 0) {
        this.queryParam.wxOpenIds = this.aaa.toString()
      } else {
        this.queryParam.wxOpenIds = ''
      }
      var param = Object.assign({}, this.queryParam);
      param.current = this.ipagination.current;
      param.size = this.ipagination.pageSize;
      return filterObj(param);
    },
    // 品牌下拉
    getBrandList() {
      brandList()
        .then(res => {
          if (res.code === 200) {
            this.brandOption = res.data
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
        .catch(err => {})
    },
    searchReset() {
      this.queryParam = {
        current: 1,
        size: 10,
        type: this.queryParam.type
      }
      this.aaa = []
      this.clearData()
      this.loadData(1);
    },
    // 点击切换tab
    callback(key) {
      console.log(key);
      this.queryParam.type = key
      this.clearData()
      this.searchQuery()
    },
    handlesync() {
      syncData().then(res => {
        console.log(res);
        if (res.code == 200) {
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    handlesync1() {
      syncData({'type':1}).then(res => {})
    },
    // 欢迎语设置
    hyy(record) {
      this.$router.push(`/marketingCenter/code/shopperscode/set`)
    },
    // 查看规则
    handelecreat(record) {
      this.$router.push(
        `/marketingCenter/code/shopperscode/rule/id=${record.id}=${record.welcomeId}`,
      )
    },
    selectAll() {
      this.selectshow = false
      this.qxselectshow = trueDependencies
      let length = this.dataSource.map((el,index) =>{
        console.log(el,'el---');
        return index
      })
      let ids = this.dataSource.map((el,index) =>{
        return el.id
      })
      this.ids = ids.join(',')
      this.selectedTableRow = length
    },
    // table取消全选
    unselect() {
      this.clearData()
    },
    // 全选后的下载二维码
    downloadewm() {
      downloadQrcodeBatch({ids:this.ids}).then(res => {
        if (res.code == 200) {
          this.$message.success('数据下载中，请在“下载中心”查看任务进度～');
          this.clearData()
        }
      })
    },
    // 全选后设置欢迎语规则
    sethyyrule() {
      this.qwrulevisible = true;
      this.getAllCpWelcome()
    },
    // 企微导购码欢迎语规则-确认按钮
    qwruleOk() {
      let ids = this.ids
      let welcomeId = this.welcomeId
      setWelcomeBatch({
        ids:ids,
        welcomeId:welcomeId
      }).then(res => {
        if(res.code == 200) {
          this.$message.success('操作成功')
          this.qwrulevisible = false;
          this.clearData()
          this.loadData(1);
        } else {
          this.$message.success('操作失败')
        }
      })
    },
    getAllCpWelcome() {
      AllCpWelcome().then(res =>{
        if(res.code == 200) {
          console.log(res);
          this.qwruleList = res.data
        }
      })
    },
    // 企微导购码欢迎语规则-下拉选change
    qwruleChange() {
      this.rushow = false
      console.log(this.welcomeId);
    },
    // 查看规则细节
    ruledetail() {
      this.rushow = true
      getWelcomeVoById({id:this.welcomeId}).then(res => {
        console.log(res,'查看细节');
        this.qwruledetail = {
          content:[],
          imageUrl:[],
          miniProgramDto:[],
        }
        res.data.itemList.forEach(el => {
          if (el.type == 1) {
            // this.qwruledetail.content = el.content
            this.qwruledetail.content.push(el.content)
            this.cardInfo = this.qwruledetail.content
          } else if (el.type == 2) {
            this.qwruledetail.imageUrl.push(el.imageUrl)
          } else if (el.type == 3) {
            this.qwruledetail.miniProgramDto.push(el.miniProgramDto)
          } 
        });
      })
    },
    downloadicon() {
      console.log('下载icon');
      pageDownloadVo({
        current:this.downloadipag.current,
        size:this.downloadipag.pageSize
      }).then(res => {
        console.log(res);
        if(res.code == 200) {
          this.downloadSource = res.data.records
          this.downloadipag.pageSize = res.data.size
          this.downloadipag.total = res.data.total
        }
      })
      this.visible = true
    },
    // 下载中心每条的-下载
    down() {
      console.log('下载');
    },
    handleOk() {
      this.visible = false;
    },
    clickewm(record) {
      this.removeVisible = true
      // this.qrCode = record.qrCode
      this.getdownloadQrcode(record.id)
    },
    getdownloadQrcode(id) {
      downloadQrcode({id}).then(res => {
        if (res.code == 200) {
          this.qrCode = res.data.url
          this.qrCodeName = res.data.name
        }
      })
    },
    clickCode() {
      console.log('下载');
      this.removeVisible = false
      this.downloadIamge(this.qrCode, this.qrCodeName);
    },
    downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");

        var a = document.createElement("a");
        var event = new MouseEvent("click");
        a.download = name || "photo";
        a.href = url; 
        a.dispatchEvent(event);
      };
      image.src = imgsrc;
    },
    handleTableChange(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination,'1111')
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.ipagination.pageSize = pagination.pageSize;
      this.ipagination.current = pagination.current;
      this.loadData()
      this.clearData()
    },
    handleTableChange1(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      console.log(pagination,'1111')
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field;
        this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
      }
      this.downloadipag.pageSize = pagination.pageSize;
      this.downloadipag.current = pagination.current;
      this.downloadicon()
    },
    clearData() {
      this.selectedTableRow = []
      this.ids = ''
      this.selectshow = true
      this.qxselectshow = false
    },
    handleExpressBlur(e) {
      this.welcomeId = e
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
  }
}
</script>

<style scoped lang="less">
  .qwruletitle {
    font-weight: 600;
    margin-bottom: 10px;
  }
  .detailbox {
    text-decoration: underline;
    vertical-align: bottom;
  }
  .detailbox1 {
    margin-top: 20px;
    border-radius: 5px;
    padding: 20px;
    background-color: #ccc;
    img {
      width: 100px;
      height: 100px;
    }
    .content {
      margin-bottom: 10px;
    }
    .item {
      margin-bottom: 20px;
    }
  }
  .download {
    width: 45px;
    height: 45px;
    position: absolute;
    bottom: 27px;
    right: 15px;
    cursor:pointer;
  }
  .downloadTitle {
    font-weight: 600;
    font-size: 20px;
    color: #000;
    margin-bottom: 20px;
  }
  /* @import '~@assets/less/common.less' */
</style>